<template>
  <view class="container">
    <!-- 台球馆信息展示 -->
    <view class="hall-info">
      <image :src="hall.imageUrl" class="hall-image" mode="widthFix"></image>
      <view class="hall-details">
        <text class="hall-name">{{hall.name}}</text>
        <view class="hall-address">{{hall.address}}</view>
        <view class="hall-distance">{{hall.distance}}</view>
        <view class="hall-phone" @click="makePhoneCall">联系电话: {{hall.phone || mockPhoneNumbers[Math.floor(Math.random() * mockPhoneNumbers.length)]}}</view>
      </view>
    </view>
    
    <!-- 台球桌状态展示 -->
    <view class="tables-container">
      <text class="section-title">台球桌状态 (空闲: {{availableTables}}/{{totalTables}})</text>
      <view class="status-legend">
        <view class="legend-item">
          <view class="dot available"></view>
          <text>空闲</text>
        </view>
        <view class="legend-item">
          <view class="dot occupied"></view>
          <text>占用</text>
        </view>
        <view class="legend-item">
          <view class="dot reserved"></view>
          <text>已预定</text>
        </view>
        <view class="legend-item" style="margin-left: auto;">
          <text>桌台刷新倒计时：{{countdown}}秒</text>
        </view>
      </view>
      <view class="tables-grid">
        <view 
          class="table-item" 
          v-for="(table, index) in tables" 
          :key="index"
          :class="{ 'available': table.status === 'available', 'occupied': table.status === 'occupied', 'reserved': table.status === 'reserved' }"
          @click="selectTable(table)"
        >
          {{table.number}}
        </view>
      </view>
    </view>
    
    
    <!-- 预约说明 -->
    <view class="notice-container">
      <text class="notice-title">预约须知</text>
      <view class="notice-content">
        <text class="notice-item">1. 预约15分钟后未到店将自动取消预约</text>
        <text class="notice-item">2. 请按时到店，避免影响他人使用</text>
        <text class="notice-item">3. 如需取消预约，请提前联系商家</text>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        title: '',
        mockPhoneNumbers: [
          '13800138000',
          '13900139000',
          '13700137000'
        ],
        hallId: '',
        hall: {},
        availableTables: 0,
        totalTables: 0,
        tables: [],
        timers: new Map(),
        development: process.env.NODE_ENV === 'development',
        userReservedTable: null,
        countdown: 10,
        countdownTimer: null
      }
    },
    onLoad(options) {
      if(options.hall) {
        const hall = JSON.parse(decodeURIComponent(options.hall))
        this.hall = hall
        // 增加模拟经纬度字段，若不存在则补充
        if (!this.hall.latitude) this.hall.latitude = 39.909;
        if (!this.hall.longitude) this.hall.longitude = 116.39742;
        this.title = hall.name
        this.hallId = hall.id
        this.availableTables = hall.availableTables
        this.totalTables = hall.totalTables
        
        // 如果没有实际电话号码，则分配一个模拟号码并保持不变
        if (!this.hall.phone) {
          this.hall.phone = this.mockPhoneNumbers[Math.floor(Math.random() * this.mockPhoneNumbers.length)];
        }
        
        // 检查台球馆是否营业
        if(!hall.isOpen) {
          uni.showModal({
            title: '提示',
            content: '该台球馆已打烊，暂不能预约',
            showCancel: false,
            confirmText: '知道了'
          })
        }
        
        // 生成台球桌状态数组
        this.tables = Array.from({length: hall.totalTables}, (_, i) => ({
          id: `${this.hall.id}_${i+1}`,
          number: `${i+1}号桌`,
          status: i < hall.availableTables ? 'available' : 'occupied'
        }))
        
        // 从本地存储加载桌台状态
        const savedTables = uni.getStorageSync(`tables_${this.hall.name}`)
        if(savedTables) {
          this.tables = this.tables.map(table => {
            const savedTable = savedTables.find(t => t.id === table.id)
            return savedTable ? savedTable : table
          })
          this.availableTables = this.tables.filter(t => t.status === 'available').length
        }
        
        // 检查本地存储中是否有已预定的桌台
        const reservedTableInfo = uni.getStorageSync(`reservedTable_${this.hall.name}`)
        if(reservedTableInfo) {
          const table = this.tables.find(t => t.id === reservedTableInfo.id)
          if(table) {
            const now = Date.now();
            if (now >= reservedTableInfo.expireTime) {
              // 预约已过期，直接取消
              table.status = 'available';
              uni.removeStorageSync(`reservedTable_${this.hall.name}`);
              uni.setStorageSync(`tables_${this.hall.name}`, this.tables);
              console.log(`[预约自动取消] 页面加载时检测到桌台 ${table.number} 预约已过期，自动取消`); // 添加日志
            } else {
              // 预约未过期，设置状态并启动定时器
              table.status = 'reserved';
              this.userReservedTable = reservedTableInfo.id;
              this.availableTables = this.tables.filter(t => t.status === 'available').length; // 重新计算可用桌数

              const remainingTime = reservedTableInfo.expireTime - now;
              const timer = setTimeout(() => {
                // 定时器触发时再次检查状态，防止重复取消
                const currentTable = this.tables.find(t => t.id === reservedTableInfo.id);
                if (currentTable && currentTable.status === 'reserved') {
                    currentTable.status = 'available';
                    this.availableTables++;
                    this.timers.delete(table.id);
                    this.userReservedTable = null;
                    uni.removeStorageSync(`reservedTable_${this.hall.name}`);
                    uni.setStorageSync(`tables_${this.hall.name}`, this.tables);
                    uni.showToast({
                      title: '预约已超时自动取消',
                      icon: 'none'
                    });
                }
              }, remainingTime);
              this.timers.set(table.id, timer);
            }
          }
        }
        // 更新可用桌台数量（确保在检查完本地存储后更新）
        this.availableTables = this.tables.filter(t => t.status === 'available').length;
        
        // 设置双轨数据更新机制
        // 1. 本地存储保持最新状态
        // 2. 定时从服务器获取最新数据
        this.refreshTimer = setInterval(() => {
          this.fetchTableStatus();
          // 保存当前状态到本地存储
          uni.setStorageSync(`tables_${this.hall.name}`, this.tables)
        }, 10000)
        
        // 启动倒计时定时器
        this.countdownTimer = setInterval(() => {
          this.countdown--;
          if(this.countdown === 0) {
            this.countdown = 10;
            this.fetchTableStatus();
          }
        }, 1000);
        
        uni.setNavigationBarTitle({
          title: this.title
        })
      }
    },
    onUnload() {
      // 清除所有定时器
      if(this.refreshTimer) {
        clearInterval(this.refreshTimer);
      }
      if(this.countdownTimer) {
        clearInterval(this.countdownTimer);
      }
      // 清除所有预约相关的定时器
      this.timers.forEach(timer => clearTimeout(timer));
      this.timers.clear();
    },
    
    methods: {
      fetchTableStatus() {
        // 如果台球馆已打烊，则将所有桌台状态设为占用
        if(!this.hall.isOpen) {
          this.tables = this.tables.map(table => ({
            ...table,
            status: 'occupied'
          }));
          this.availableTables = 0;
          return;
        }
        
        // 双轨数据更新机制
        // 1. 先检查本地存储是否有更新
        const savedTables = uni.getStorageSync(`tables_${this.hall.name}`)
        if(savedTables) {
          // 保留用户已预定的桌台状态
          const reservedTableId = this.userReservedTable;
          this.tables = this.tables.map(table => {
            if(reservedTableId && table.id === reservedTableId) {
              return { ...table, status: 'reserved' };
            }
            const savedTable = savedTables.find(t => t.id === table.id);
            return savedTable ? { ...table, status: savedTable.status } : table;
          });
          this.availableTables = this.tables.filter(t => t.status === 'available').length;
        }
        
        // 2. 调用API获取最新桌台状态
        // 模拟API返回数据，只随机改变部分桌台状态
        const isAdmin = this.$store?.state?.user?.role === 'admin';
        const changedTables = this.tables
          .filter(() => Math.random() > 0.7) // 约30%的桌台会改变状态
          .map(table => ({
            id: table.id,
            status: isAdmin 
              ? (Math.random() > 0.5 ? 'available' : 'occupied')
              : table.status === 'available' 
                ? 'available' // 普通用户时，空闲状态保持不变
                : table.status
          }));
        
        // 只更新状态发生变化的桌台，但保留用户已预定的桌台状态
        this.tables = this.tables.map(table => {
          if(this.userReservedTable && table.id === this.userReservedTable) {
            return { ...table, status: 'reserved' };
          }
          const changedTable = changedTables.find(t => t.id === table.id);
          return changedTable 
            ? { ...table, status: changedTable.status }
            : table;
        });
        
        // 更新空闲桌台数量
        this.availableTables = this.tables.filter(t => t.status === 'available').length;
        
        // 保存更新后的状态到本地存储
        uni.setStorageSync(`tables_${this.hall.name}`, this.tables);
        
        // 立即更新界面
        this.$forceUpdate();
      },
      makePhoneCall() {
        const phone = this.hall.phone || this.mockPhoneNumbers[Math.floor(Math.random() * this.mockPhoneNumbers.length)];
        uni.showModal({
          title: '拨打电话',
          content: `确定要拨打 ${phone} 吗？`,
          success: (res) => {
            if (res.confirm) {
              uni.makePhoneCall({
                phoneNumber: phone
              });
            }
          }
        });
      },
      selectTable(table) {
        if(this.userReservedTable) {
          uni.showModal({
            title: '提示',
            content: '您已预定桌台，不能重复预定',
            showCancel: false,
            confirmText: '知道了'
          })
          return;
        } else if(table.status === 'occupied') {
          uni.showModal({
            title: '提示',
            content: '该桌台已被占用，请选择其他桌台',
            showCancel: false,
            confirmText: '知道了'
          })
        } else if(table.status === 'reserved') {
          uni.showModal({
            title: '提示',
            content: '该桌台已被预定，请选择其他桌台',
            showCancel: false,
            confirmText: '知道了'
          })
        } else {
          uni.showModal({
            title: '确认预约',
            content: '',
            editable: true,
            placeholderText: '请输入11位手机号',
            success: (res) => {
              if (res.confirm && res.content) {
                const phone = res.content.trim();
                if(!/^\d{11}$/.test(phone)) {
                  uni.showToast({
                    title: '请输入11位有效手机号码',
                    icon: 'none'
                  });
                  return;
                }
                table.status = 'reserved';
                this.availableTables--;
                this.phone = phone;
                this.userReservedTable = table.id;
                const expireTime = Date.now() + 30 * 1000; // 30秒后过期
                const expireDate = new Date(expireTime);
                const formattedExpireTime = expireDate.toLocaleString(); // 格式化时间
                // 保存预定信息到本地存储，包含过期时间戳
                uni.setStorageSync(`reservedTable_${this.hall.name}`, {
                  id: table.id,
                  phone: phone,
                  expireTime: expireTime
                });
                // 更新桌台状态到本地存储
                uni.setStorageSync(`tables_${this.hall.name}`, this.tables);
                // 立即更新界面
                this.$forceUpdate();

                // 设置30秒自动取消定时器
                const timer = setTimeout(() => {
                  // 定时器触发时检查状态
                  const currentTable = this.tables.find(t => t.id === table.id);
                  if (currentTable && currentTable.status === 'reserved' && this.userReservedTable === table.id) {
                      currentTable.status = 'available';
                      this.availableTables++;
                      this.timers.delete(table.id);
                      this.userReservedTable = null;
                      uni.removeStorageSync(`reservedTable_${this.hall.name}`);
                      uni.setStorageSync(`tables_${this.hall.name}`, this.tables);
                      console.log(`[预约自动取消] 桌台 ${currentTable.number} 预约超时，自动取消`); // 添加日志
                      uni.showToast({
                        title: '预约已超时自动取消',
                        icon: 'none'
                      });
                  }
                }, 30000);
                this.timers.set(table.id, timer);

                uni.showToast({
                  title: '预约成功',
                  icon: 'success'
                });
                // 修改日志，增加预计取消时间
                console.log(`[预约成功] 用户 ${phone} 成功预约桌台 ${table.number}，预计将在 ${formattedExpireTime} 自动取消`);
              }
            }
          });
        }
      }
    }
  }
</script>

<style>
  .container {
    padding: 20rpx;
  }
  
  .hall-info {
    display: flex;
    margin-bottom: 30rpx;
    border-bottom: 1px solid #eee;
    padding-bottom: 20rpx;
  }
  
  .hall-image {
    width: 200rpx;
    height: 150rpx;
    border-radius: 10rpx;
    margin-right: 20rpx;
  }
  
  .hall-details {
    flex: 1;
  }
  
  .hall-name {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 10rpx;
  }
  
  .hall-address, .hall-distance {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 5rpx;
  }
  
  .hall-phone {
    font-size: 28rpx;
    color: #007AFF;
    text-decoration: underline;
    margin-bottom: 5rpx;
  }
  
  .hall-phone:active {
    opacity: 0.7;
  }
  
  .tables-container {
    margin-bottom: 30rpx;
  }
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    display: block;
  }
  
  .tables-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
  }
  
  .table-item {
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 10rpx;
    font-size: 28rpx;
  }
  
  .table-item.available {
    background-color: #07C160;
    color: #fff;
  }
  
  .table-item.occupied {
    background-color: #FF0000;
    color: #fff;
  }
  
  .table-item.reserved {
    background-color: #FFCC00;
    color: #fff;
  }
  
  .status-legend {
    display: flex;
    justify-content: flex-start;
    gap: 40rpx;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
  }
  
  .notice-container {
    margin-top: 40rpx;
    padding: 20rpx;
    background-color: #f8f8f8;
    border-radius: 10rpx;
  }
  
  .notice-title {
    font-size: 28rpx;
    font-weight: bold;
    margin-bottom: 15rpx;
    display: block;
  }
  
  .notice-content {
    display: flex;
    flex-direction: column;
    gap: 10rpx;
  }
  
  .notice-item {
    font-size: 24rpx;
    color: #666;
  }
  
  .legend-item {
    display: flex;
    align-items: center;
    gap: 10rpx;
    font-size: 26rpx;
  }
  
  .dot {
    width: 20rpx;
    height: 20rpx;
    border-radius: 50%;
  }
  
  .dot.available {
    background-color: #07C160;
  }
  
  .dot.occupied {
    background-color: #FF0000;
  }
  
  .dot.reserved {
    background-color: #FFCC00;
  }
  
  .header {
    margin-bottom: 30rpx;
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
  }
  
  .form-container {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }
  
  .form-item {
    display: flex;
    flex-direction: column;
    gap: 10rpx;
  }
  
  .label {
    font-size: 28rpx;
    color: #666;
  }
  
  .picker {
    padding: 20rpx;
    border: 1px solid #eee;
    border-radius: 8rpx;
    font-size: 28rpx;
  }
  
  .submit-btn {
    margin-top: 40rpx;
    background-color: #07C160;
    color: #fff;
    border-radius: 40rpx;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 32rpx;
  }
</style>